<?php

namespace App\Http\Imports\BaseData;


use App\Models\Company;
use App\Models\CompanyCategory;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class CompanyImport implements ToCollection
    {
    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
        {
        //分组	编号	简称		单位全称	联系人	联系人手机	信用额度	备注
        set_time_limit(0);
        $collection->filter(function ($v, $k)
            {
            if ($k == 0) {
                return;
                }
            $category_name = $v[0];
            $code          = $v[1];
            $name          = $v[2];
            $fullname      = $v[3];
            $linkman_name  = $v[4];
            $linkman_phone = $v[5];
            $credit_limit  = $v[6] ?? 0;
            $remark        = $v[7];

            $categ_m = CompanyCategory::whereName(trim($category_name))->first();
            if ($categ_m) {
                $category_id = $categ_m->id;
                }
            else {
                fail("{$category_name}分组不存在！");
                }
            if (isEmpty($code)) {
                fail("第" . $k . "行往来单位编号不存在！！导入失败！");
                }
            if (isEmpty($name)) {
                fail("第" . $k . "行往来单位名称不存在！！导入失败！");
                }
            $com_data = Company::whereCode(trim($code))->first();
            if ($com_data) {
                fail("往来单位编号{$code}已存在！导入失败！");
                }

            Company::create([
                'code'                => $code,
                'name'                => $name,
                'fullname'            => $fullname,
                'linkman_name'        => $linkman_name,
                'linkman_mobilephone' => $linkman_phone,
                'linkman_phone'       => $linkman_phone,
                'finance_id'          => $categ_m->finance_id,
                'phone'               => $linkman_phone,
                'credit_limit'        => $credit_limit,
                'remark'              => $remark,
                'category_id'         => $category_id,
            ]);
            });

        }
    }
